<template>
  <div>
    <!-- 操作按钮 -->
    <a-button type="primary" @click="del" :disabled="isDelAble">删除</a-button>
    <!-- form+modal -->
    <a-button type="primary" @click="showModalAdd()"  style="margin-left: 10px;">添加</a-button>
    <a-button type="primary" @click="showModalEdit()" :disabled="isAble" style="margin-left: 10px;">修改</a-button>
    <menu-modal ref="modal" @ok="handleSaveOk" @close="handleSaveClose"></menu-modal>

    <!-- 查询表单 -->
    <a-form
      layout="inline"
      :form="form"
      @submit="handleSubmit"
      style="margin-top:10px">
      <a-form-item :validate-status="userNameError() ? 'error' : ''" :help="userNameError() || ''">
        <a-input
          v-decorator="[
            'name',
            { rules: [{ required: true, message: 'Please input your name!' }] },
          ]"
          placeholder="name"
        >
          <a-icon slot="prefix" type="user" style="color:rgba(0,0,0,.25)" />
        </a-input>
      </a-form-item>
      <a-form-item :validate-status="passwordError() ? 'error' : ''" :help="passwordError() || ''">
        <a-input
          v-decorator="[
            'id',
            { rules: [{ required: true, message: 'Please input your id!' }] },
          ]"
          placeholder="id"
        >
          <a-icon slot="prefix" type="lock" style="color:rgba(0,0,0,.25)" />
        </a-input>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit" :disabled="hasErrors(form.getFieldsError())">
          Log in
        </a-button>
      </a-form-item>
    </a-form>
    <!-- 从后台动态获取数据 -->
    <a-table :columns="columns" :dataSource="dataMenu" :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}" @change="handleTableChangeForMenu"/>

  </div>
</template>
<script>
  import { mapActions } from 'vuex'
  import ModalAdd from '@/components/ModalAdd'
  import MenuModal from './modules/MenuModal.vue'
  const columns = [{
      title: 'Name',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: 'component',
      dataIndex: 'component',
      key: 'component',
      width: '12%'
    },
    {
      title: 'id',
      dataIndex: 'id',
      key: 'id',
      width: '12%'
    },
    {
      title: 'meta',
      dataIndex: 'meta',
      key: 'meta',
      width: '12%'
    },
    {
      title: 'des',
      dataIndex: 'des',
      width: '30%',
      key: 'des'
    }
  ];
  function hasErrors (fieldsError) {
    return Object.keys(fieldsError).some(field => fieldsError[field]);
  }

  export default {
    name: 'Menu',
    components: {
      ModalAdd,
      MenuModal
    },
    data () {
      return {
        pagination: { 'pageNum': 1, 'pageSize': 5 },
        loading: false,
        dataMenu: [],
        columns,
        hasErrors,
        form: this.$form.createForm(this, { name: 'horizontal_login' }),
        selectedRowKeys: [],
        isAble: true,
        isDelAble: true,
        mdl: {}
      };
    },
    mounted () {
      this.$nextTick(() => {
        // To disabled submit button at the beginning.
        this.form.validateFields();
      });
      this.fetchs({
          pageSize: 5,
          pageNum: 1
      });
      this.fetchs2({
          pageSize: 5,
          pageNum: 1
      });
    },
    methods: {
      ...mapActions(['MenuGet', 'MenuAdd', 'MenuList', 'Menus', 'MenuDel']),
      edit (record) {
        debugger;
        const { form: { setFieldsValue } } = this
        this.visible = true
        this.$nextTick(() => {
          setFieldsValue({ taskName: 'test' })
        })
      },
       // 处理添加方法
      showModalAdd () {
        this.$refs.modal.add()
        this.$refs.modal.dialogStatus = 'add'
      },
      // 处理编辑的方法
      showEditModal2 () {
        this.type = 'edit';
        this.visible = true;
      },
      onSelectChange (selectedRowKeys) {
         this.$message.info('sel3ect')
        debugger;
        // console.log('selectedRowKeys changed: ', selectedRowKeys);
        this.selectedRowKeys = selectedRowKeys;
        if (this.selectedRowKeys.length >= 1) {
          this.isDelAble = false
          this.$message.info(this.isDelAble)
        } else {
          this.isDelAble = true
        }
        if (this.selectedRowKeys.length === 1) {
          this.isAble = false
          this.$message.info(this.selectedRowKeys.length)
        } else {
          this.isAble = true
          this.$message.info(this.selectedRowKeys.length)
        }
      },
      userNameError () {
            const { getFieldError, isFieldTouched } = this.form;
            return isFieldTouched('name') && getFieldError('name');
      },
      // Only show error after a field is touched.
      passwordError () {
        const { getFieldError, isFieldTouched } = this.form;
        return isFieldTouched('id') && getFieldError('id');
      },
      handleSubmit (e) {
        debugger
        const {
          MenuGet
        } = this
        e.preventDefault();
        this.form.validateFields((err, values) => {
          if (!err) {
            // console.log('Received values of form: ', values);
            const menuParams = { ...values }
            menuParams.name = values.name
            MenuGet(menuParams)
              .then((res) => {
                console.log(res)
              })
              .catch(err => this.requestFailed(err))
              .finally(() => {
                // console.log('菜单获取，finally')
                this.fetchs({
                  pageSize: 5,
                  pageNum: 1
                });
              })
          }
        });
      },

      handleTableChange (pagination, filters, sorter) {
        debugger
        // console.log(pagination);
        const pager = { ...this.pagination };
        pager.current = pagination.current;
        this.pagination = pager;
        this.fetchs({
          pageSize: pagination.pageSize,
          pageNum: pagination.current,
          sortField: sorter.field,
          sortOrder: sorter.order,
          ...filters
        });
      },
      fetchs (params = {}) {
        debugger
        const {
          MenuList
        } = this
        // console.log('params:', params);
        this.loading = true;
        MenuList({
            params
        }).then(data => {
          const pagination = { ...this.pagination };

          // Read total count from server
          // pagination.total = data.totalCount;
          pagination.total = data.total;
          // pagination.pageSize = data.pageSize;
          // pagination.current = data.pageNmn;
          this.loading = false;
          this.pagination = pagination;
          // console.log('this.pagination' + this.pagination)
        });
      },
      handleTableChangeForMenu (pagination, filters, sorter) {
        debugger
        // console.log(pagination);
        const pager = { ...this.pagination };
        pager.current = pagination.current;
        this.pagination = pager;
        this.fetchs2({
          pageSize: pagination.pageSize,
          pageNum: pagination.current,
          sortField: sorter.field,
          sortOrder: sorter.order,
          ...filters
        });
      },
      fetchs2 (params = {}) {
        debugger
        const {
          Menus
        } = this
        this.loading = true;
        Menus({
            params
        }).then(data => {
          this.isAble = true;
          this.$message.info(data.total)
          const pagination = { ...this.pagination };
          pagination.total = data.total;
          this.loading = false;
          this.dataMenu = JSON.parse(data.results);
          this.pagination = pagination;
        });
      },
      showModalEdit () {
         var s = this.selectedRowKeys[0]
         // this.$message.info('modal update=' + this.selectedRowKeys[0])
         const {
           MenuGet
         } = this
         MenuGet({
             id: s
         }).then(data => {
           debugger
           this.mdl = Object.assign({}, data.result)
           this.$refs.modal.edit(this.mdl);
           console.log(data)
         });
        debugger;
      },
      handleCancel () {
        this.visible = false;
      },
      del (selectedRowKeys) {
        this.$confirm({
          title: '警告',
          content: `真的要删除吗?`,
          okText: '删除',
          okType: 'danger',
          cancelText: '取消',
          onOk () {
            console.log('OK')
            // 在这里调用删除接口
            return new Promise((resolve, reject) => {
              setTimeout(Math.random() > 0.5 ? resolve : reject, 1000)
            }).catch(() => console.log('Oops errors!'))
          },
          onCancel () {
            console.log('Cancel')
          }
        })
        // console.log(this.selectedRowKeys[0])
        // const id = this.selectedRowKeys[0];
        // this.$message.info(id)
        // const {
        //   MenuDel
        // } = this
        // // console.log('params:', id);
        // this.loading = true;
        // MenuDel({
        //     id
        // }).then(data => {
        //   // console.log('data' + data)
        // });

        // this.fetchs2({
        //     pageSize: 5,
        //     pageNum: 1
        // });
        // this.selectedRowKeys = []
      }
    }
  };

</script>
